package com.fs.sys.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.fs.sys.bean.dto.AppCategoryDTO;
import com.fs.sys.bean.dto.AppDTO;
import com.fs.sys.bean.query.AppQuery;
import com.fs.sys.bean.resp.CategoryAppResp;
import com.fs.sys.entityservice.AppCategoryEntityService;
import com.fs.sys.entityservice.AppEntityService;
import com.fs.common.annotations.Log;
import com.fs.common.bean.LogType;
import com.fs.common.bean.UserContextHolder;
import com.fs.common.exception.AppException;
import com.fs.sys.bean.enums.AppUseLimitType;
import com.fs.common.ErrorCodes;
import com.fs.sys.service.UserAppService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.fs.common.AppConstants.SUPER_TENANT;

/**
 * 应用控制器 
 * @author Coder Generator 2025-06-06 11:03:07 
 **/
@RestController
@RequestMapping("/sys/app")
@Slf4j
@Tag(name = "应用控制器")
public class AppController {
    @Autowired
    private AppEntityService service;

    @Autowired
    private UserAppService appService;

    @Autowired
    private AppCategoryEntityService categoryEntityService;

    @PostMapping("add")
    @Operation(summary = "新增")
    @Log(value = "应用", op = LogType.NEW)
    public void add(@RequestBody @Validated AppDTO req) {
        req.setStatus(1);
        req.setSecret(UUID.randomUUID().toString().replace("-", ""));

        // 新增应用，如果是超级租户，那么应用限制类型是auth，否则是private，公共的应用通过脚本初始化而不在此添加
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        if (tenantId.equals(SUPER_TENANT)) {
            req.setUseLimitType(AppUseLimitType.AUTH);
        } else {
            req.setUseLimitType(AppUseLimitType.PRIVATE);
        }

        service.insert(req);
    }

    @PutMapping("update")
    @Operation(summary = "更新")
    @Log(value = "应用", op = LogType.EDIT)
    public void update(@RequestBody @Validated AppDTO req) {
        // 租户权限检查，只能改自己租户的应用
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        String appId = req.getId();
        AppDTO app = service.findById(appId).orElseThrow(AppException.supplier(ErrorCodes.APP_NOT_EXISTS));
        if (app.getTenantId().equals(tenantId)) {
            service.update(req);
        } else {
            log.error("非本租户应用，不能进行修改");
            throw new IllegalArgumentException();
        }
    }

    @DeleteMapping("delete/{id}")
    @Operation(summary = "删除")
    @Log(value = "应用", op = LogType.DELETE)
    public void delete(@PathVariable("id") String id) {
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        AppDTO app = service.findById(id).orElseThrow(AppException.supplier(ErrorCodes.APP_NOT_EXISTS));
        if (app.getTenantId().equals(tenantId)) {
            service.delete(id);
        } else {
            log.error("非本租户应用，不能进行修改");
            throw new IllegalArgumentException();
        }
    }

    @GetMapping("detail/{id}")
    @Operation(summary = "根据id查找记录")
    public AppDTO findById(@PathVariable("id") String id) {
        return service.findById(id).orElse(null);
    }

    @GetMapping("find-by-code")
    public AppDTO findByCode(String code) {
        return service.queryBuilder()
                .eq("code", code)
                .findOne()
                .orElse(null);
    }

    /**
     * 获取登录用户应用列表
     */
    @GetMapping("mine")
    public List<AppDTO> myApps() {
        String userId = UserContextHolder.getUserIdOrThrow();
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        return appService.findByUserCanVisit(tenantId, userId);
    }

    /**
     * 分页查询租户本身应用
     * @param query 查询条件
     * @return 租户本身应用
     */
    @PostMapping("page-query")
    @Operation(summary = "查询-分页")
    public IPage<AppDTO> pageQuery(@RequestBody AppQuery query) {
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        query.setTenantId(tenantId);
        return service.pageQuery(query);
    }

    /**
     * 查询租户本身的应用
     * @param query 查询结果
     * @return 租户本身应用
     */
    @PostMapping("query")
    @Operation(summary = "查询-不分页")
    public List<AppDTO> query(@RequestBody AppQuery query) {
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        query.setTenantId(tenantId);
        return service.query(query);
    }

    /**
     * 获取当前租户可访问应用列表
     * @return 当前租户可访问应用列表
     */
    @GetMapping("tenant-can-visit")
    public List<AppDTO> getTenantCanVisitApps() {
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        return appService.findByTenantCanVisit(tenantId);
    }

    @GetMapping("regenerate-secret")
    @Log(value = "应用", op = LogType.EDIT)
    public String regenerateSecret(String id) {
        String secret = UUID.randomUUID().toString().replace("-", "");
        service.updateBuilder()
                .eq("id", id)
                .set("secret", secret)
                .update();
        return secret;
    }

    /**
     * 根据分类组装应用并返回
     * @return 按分类分组的应用列表
     */
    @GetMapping("group-by-category")
    public List<CategoryAppResp> getAppsGroupByCategory() {
        String userId = UserContextHolder.getUserIdOrThrow();
        String tenantId = UserContextHolder.getTenantIdOrThrow();
        List<AppDTO> apps = appService.findByUserCanVisit(tenantId, userId);
        if (CollectionUtils.isEmpty(apps)) {
            return new ArrayList<>(16);
        }

        Map<String, List<AppDTO>> appMap = apps.stream()
                .collect(Collectors.groupingBy(AppDTO::getCategoryId));

        List<AppCategoryDTO> categoryList = categoryEntityService.findAll("sort");
        if (CollectionUtils.isEmpty(categoryList)) {
            return new ArrayList<>(16);
        }

        return categoryList.stream()
                .map(category -> {
                    CategoryAppResp resp = new CategoryAppResp();
                    resp.setCategoryId(category.getId());
                    resp.setCategoryName(category.getName());
                    resp.setApps(appMap.get(category.getId()));
                    return resp;
                })
                .filter(item -> CollectionUtils.isNotEmpty(item.getApps()))
                .toList();
    }

    /**
     * 添加使用次数
     */
    @GetMapping("add-used-count")
    public void addUsedCount(String id) {
        SqlRunner.db().update("update sys_app set used_count = used_count + 1 where id = '" + id + "'");
    }
}